﻿#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

using namespace std;
const uint16_t PORT = 1234;
map<string, string> buildDict() {
	map<string, string> dict;
	dict["hello"] = "你好";
	dict["world"] = "世界";
	dict["i"] = "我";
	dict["country"] = "国家";
	dict["file"] = "文件";
	dict["abandon"] = "放弃";
	dict["body"] = "身体";
	dict["eyes"] = "眼睛";
	dict["computer"] = "电脑";
	dict["program"] = "编程";
	dict["xjtu"] = "西交";
	dict["sjtu"] = "上交";
	dict["school"] = "学校";
	for (auto& word : dict)
		dict[word.second] = word.first;
	return dict;
}
void die(const char* s) {
	perror(s);
	exit(1);
}
struct sockaddr_in serv_addr,clnt_addr;
int serv_sock = 0, clnt_sock = 0,opt = 1;
string buf = "\0";
string answer = "success";
void my_socket() {
	serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (serv_sock < 0)
		die("socket");
	setsockopt(serv_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
	// AF_INET :   表示使用 IPv4 地址		可选参数
	// SOCK_STREAM 表示使用面向连接的数据传输方式，
	// IPPROTO_TCP 表示使用 TCP 协议
}
void my_bind() {
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	//serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //具体的IP地址
	serv_addr.sin_port = htons(PORT);  //端口
	if (bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
		die("bind");
}
void my_listen() {
	if (listen(serv_sock, 20) < 0)
		die("listen");
	cout << "Server Listening...\n";
}
void my_accept() {
	socklen_t clnt_addr_size = sizeof(clnt_addr);
	clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
	if (clnt_sock < 0) {
		perror("accept");
	}
}
void my_read() {
	char buffer[32] = { 0 };
	ssize_t n = read(clnt_sock, buffer, 32);
	if (n <= 0) {
		close(clnt_sock);
		return;
	}
	buf.assign(buffer,n);
	auto pos = buf.find('\0');
	if(pos != string::npos){
		buf.erase(pos);
	}
}
void my_write() {
	write(clnt_sock, answer.c_str(), answer.size());
}
int main() {
	cout << "服务器启动" << endl;
	map<string,string> dict = buildDict();
	my_socket();
	my_bind();
	my_listen();
	while (1) {
		my_accept();
		my_read();
		cout << "服务器接收信息： " << buf << endl;
		answer = dict.find(buf) == dict.end() ? "NotFound" : dict[buf];
		my_write();
		close(clnt_sock);
	}
	close(serv_sock);
	return 0;
}
